import React from 'react'
import './index.css'

class AddTodo extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            text: ''
        };
        this.handleToggleAll = this.handleToggleAll.bind(this)
    }

    handleKeyUp(e) {
        switch (e.keyCode) {
            case 13:
                const text = this.state.text.trim();
                if (text) {
                    this.props.onAddTodo(text);
                }
                this.clearInput();
                break;
            case 27:
                this.clearInput();
                break;
            default:
                break;
        }
    }

    clearInput() {
        this.setState({
            text: ''
        })
    }

    handleInputChange(text) {
        this.setState({
            text
        })
    }

    handleToggleAll() {
        console.log("click");
        this.props.onToggleAll(!this.props.isAllCompleted)
    }

    render() {
        console.log(`add-todo ${this.props.isAllCompleted}`);
        return (
            <header className='header'>
                <input type='checkbox'
                    // TODO onchange回调不了
                    //    onChange={() => console.log("gdasg")}
                       className='toggle-all'
                       onClick={this.handleToggleAll}
                       checked={this.props.isAllCompleted}/>
                <input
                    autoFocus='autofocus'
                    autoComplete='off'
                    placeholder='What needs to be done?'
                    className='new-todo'
                    ref={input => this.textInput = input}
                    value={this.state.text}
                    onChange={() => this.handleInputChange(this.textInput.value)}
                    onKeyUp={(e) => this.handleKeyUp(e)}/>
            </header>
        )
    }
}

export default AddTodo